package com.yzh.booksystem.dao;

import com.yzh.booksystem.entity.Book;
import com.yzh.booksystem.entity.User;
import com.yzh.booksystem.utils.Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Array;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDao implements IUserDao {
    //设计一：登陆判断管理员用户是否存在方法
    public User isUserExit(User user) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(Utils.getDataSource());
        String sql = "select * from user where name=?";
        User users = (User)queryRunner.query(sql, new BeanHandler(User.class), user.getName());//创建BeanHandler对象并将查到的数据封装到User对象
        // 中,User.class是要将数据映射到哪个类里面的对象
        if (users != null) {
            return users;
        } else {
            return null;
        }
    }
    //设计二：设计管理员登录进去后页面显示数据库中所有图书信息
    /*1.返回类型为集合类型
      2.所有的数据对象为集合类型
     */
    public List<Book> check_total_books() throws SQLException {
        QueryRunner queryRunner = new QueryRunner(Utils.getDataSource());
        String sql = "select * from book";
        ArrayList<Book> listBooks = (ArrayList<Book>) queryRunner.query(sql, new BeanListHandler(Book.class));
        if (listBooks != null) {
            return listBooks;
        } else {
            return null;
        }
    }
    //设计三：在index.jsp页面单个查询
    public Book check_single_book(Book book) throws SQLException {
        QueryRunner queryRunner = new QueryRunner(Utils.getDataSource());
        String sql = "select * from book where bookname=?";//点击查找按钮后一直白屏在updateServlet中就是因为这个名字写错了，找不到数据
        Book book1= queryRunner.query(sql, new BeanHandler<>(Book.class), book.getBookname());
        if (book1 != null) {
            return book1;
        } else {
            return null;
        }
    }
//    public boolean addUser(User user) throws SQLException {
//        QueryRunner queryRunner = new QueryRunner(Utils.getDataSource());
//        String sql = "insert into user(id, name, password, email) values(?, ?, ?, ?)";
//        Object[] params = { user.getName(), user.getPassword() };
//        int num = queryRunner.update(sql, params);
//        if (num > 0) {
//            return true;
//        } else {
//            return false;
//        }
//    }
}
